<template>
  <div>
    <div class="user-container">
      <!--  左边卡片    -->
      <el-card class="user-profile" shadow="hover" :body-style="{ padding: '0px' }">
        <!--   背景     -->
        <div class="user-profile-bg"></div>
        <!--    头像    -->
        <div class="user-avatar-wrap">
          <el-avatar class="user-avatar" :size="120" :src="userStore.avatarUrl" />
        </div>
        <!--   用户信息     -->
        <div class="user-info">
          <div class="info-name">{{ userStore.realName }}</div>
          <div class="info-desc">
            <span>@{{ userStore.nickname }}</span>
            <el-divider direction="vertical" />
            <el-link href="https://blog.zhangjianyong.top" target="_blank">blog</el-link>
          </div>
          <div class="info-desc">{{ userStore.description }}</div>
          <div class="info-icon">
            <a :href="userStore.gitee" target="_blank">
              <el-icon>
                <svg class="icon" aria-hidden="true">
                  <use xlink:href="#icon-gitee"></use>
                </svg>
              </el-icon>
            </a>
            <a :href="userStore.github" target="_blank">
              <el-icon>
                <svg class="icon" aria-hidden="true">
                  <use xlink:href="#icon-GitHub"></use>
                </svg>
              </el-icon>
            </a>
          </div>
        </div>
        <!--    底部信息    -->
        <div class="user-footer">
          <div class="user-footer-item">
            <el-statistic title="文章" :value="articleNum" />
          </div>
          <div class="user-footer-item">
            <el-statistic title="访问量" :value="visitsNumber" />
          </div>
        </div>
      </el-card>
      <!--   右边卡片   -->
      <el-card
        class="user-content"
        shadow="hover"
        :body-style="{ padding: '20px', height: '100%', boxSizing: 'border-box' }"
      >
        <el-tabs v-model="activeName" tab-position="left">
          <!--    消息通知      -->
          <el-tab-pane name="label1" label="消息通知" class="user-tab-pane">
            <NotificationTabs />
          </el-tab-pane>
          <!--     头像上传     -->
          <el-tab-pane name="label2" label="我的头像" class="user-tab-pane">
            <FileUpload
              :crop-height="200"
              :img="userStore.avatarUrl"
              :file-name="avatarFileName"
              :show="activeName == 'label2'"
              :upload="saveAvatar"
            />
          </el-tab-pane>
          <!--    修改信息      -->
          <el-tab-pane name="label3" label="修改信息" class="user-tab-pane">
            <UserInfoUpdate
              v-model="updateUserInfoParam"
              :fields="userInfoFields"
              :rules="userInfoRules"
            ></UserInfoUpdate>
          </el-tab-pane>
          <!--    修改密码      -->
          <el-tab-pane name="label4" label="修改密码" class="user-tab-pane">
            <UserInfoUpdate
              ref="changePasswordForm"
              v-model="changePasswordParam"
              :fields="changePasswordField"
              :rules="changePasswordRules"
            ></UserInfoUpdate>
          </el-tab-pane>
          <!--修改git-->
          <el-tab-pane name="label5" label="GIT配置" class="user-tab-pane">
            <UserInfoUpdate
              v-model="updateGitParam"
              :fields="updateGitFields"
              :rules="updateGitRules"
            ></UserInfoUpdate>
          </el-tab-pane>
          <!--个人技能-->
          <el-tab-pane name="label6" label="个人技能" class="user-tab-pane">
            <UserSkillManagement />
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { computed, ref } from 'vue'
  import NotificationTabs from '@/views/user/components/NotificationTabs.vue'
  import { useUserStore } from '@/store/user.ts'
  import 'vue-cropper/dist/index.css'
  import FileUpload from '@/views/user/components/FileUpload.vue'
  import { avatarUpload, gitUpdate, passwordChange, update } from '@/api/user.ts'
  import { ChangePwdParam, GitUpdateParam, UserUpdateParam } from '@/types'
  import { ElMessage, FormRules } from 'element-plus'
  import UserInfoUpdate from '@/views/user/components/UserInfoUpdate.vue'
  import UserSkillManagement from '@/views/user/components/UserSkillManagement.vue'
  import { Field } from '@/types/user-info-update-option.ts'

  const userStore = useUserStore()
  const articleNum = 999
  const visitsNumber = 99999

  const activeName = ref('label1')

  const avatarFileName = computed(() => userStore.avatar)

  const saveAvatar = async (file: File) => {
    let data = await avatarUpload(file)
    userStore.handleSetAvatar(data.id)
    ElMessage.success('保存成功')
  }
  /*修改密码*/
  const changePasswordForm = ref()
  const changePasswordParam = ref({ oldPassword: '', newPassword: '', newPassword1: '' })
  const handleChangePassword = async (param: unknown) => {
    await passwordChange(param as ChangePwdParam)
    ElMessage.success('密码修改成功')
    changePasswordParam.value = { oldPassword: '', newPassword: '', newPassword1: '' }
  }
  const changePasswordField: Field[] = [
    { label: '旧密码', prop: 'oldPassword', type: 'password' },
    { label: '新密码', prop: 'newPassword', type: 'password' },
    { label: '确认新密码', prop: 'newPassword1', type: 'password' },
    { label: '保存', prop: '', type: 'button', onClick: handleChangePassword },
  ]
  //修改密码表单规则
  const confirmPasswordValidator = (
    _rule: unknown,
    value: string,
    callback: (_error?: Error) => void
  ) => {
    if (!value) {
      callback(new Error('请重复密码'))
    } else if (value !== changePasswordParam.value.newPassword) {
      callback(new Error('两次输入密码不同'))
    } else {
      callback()
    }
  }
  const changePasswordRules: FormRules = {
    oldPassword: [{ required: true, message: '请输入旧密码', trigger: 'blur' }],
    newPassword: [{ required: true, message: '请输入新密码', trigger: 'blur' }],
    newPassword1: [{ validator: confirmPasswordValidator, trigger: 'blur', required: true }],
  }

  /*修改用户信息*/
  const updateUserInfoParam = ref({ ...userStore.user })
  const handleUserInfoUpdate = async (param: unknown) => {
    await update(param as UserUpdateParam)
    userStore.handleSetUserInfo(param as UserUpdateParam)
    ElMessage.success('修改成功')
  }
  const userInfoFields: Field[] = [
    { prop: 'nickname', type: 'text', label: '昵称' },
    { prop: 'realName', type: 'text', label: '姓名' },
    { prop: 'birthday', type: 'date', label: '生日', format: 'YYYY-MM-DD' },
    { prop: 'email', type: 'text', label: '邮箱' },
    { prop: 'phone', type: 'text', label: '手机号码' },
    { prop: 'location', type: 'text', label: '位置' },
    { prop: 'blogName', type: 'text', label: '博客名称' },
    { prop: 'blogDescription', type: 'textarea', label: '博客描述（完整版）' },
    { prop: 'blogSummary', type: 'text', label: '博客简述（首页显示）' },
    { prop: 'description', type: 'textarea', label: '个人描述（完整版）' },
    { prop: 'personalSummary', type: 'text', label: '个人简述（首页显示）' },
    { prop: '', type: 'button', label: '保存', onClick: handleUserInfoUpdate },
  ]

  const userInfoRules: FormRules = {
    nickname: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
    realName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    birthday: [{ required: true, message: '请输入生日', trigger: 'blur' }],
    email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }],
    phone: [{ required: true, message: '请输入手机号码', trigger: 'blur' }],
    location: [{ required: true, message: '请输入位置', trigger: 'blur' }],
    blogName: [{ required: true, message: '请输入博客名称', trigger: 'blur' }],
    blogDescription: [{ required: true, message: '请输入博客描述', trigger: 'blur' }],
    description: [{ required: true, message: '请输入个人描述', trigger: 'blur' }],
    // 简述字段为可选
    blogSummary: [{ required: false }],
    personalSummary: [{ required: false }],
  }

  /*修改git*/
  const updateGitParam = ref({ ...userStore.user })
  const handleUpdateGit = async (param: unknown) => {
    await gitUpdate(param as GitUpdateParam)
    userStore.handleSetGit(param as GitUpdateParam)
    ElMessage.success('修改成功')
  }
  const updateGitFields: Field[] = [
    { label: 'gitee', prop: 'gitee', type: 'text' },
    { label: 'github', prop: 'github', type: 'text' },
    { label: '保存', prop: '', type: 'button', onClick: handleUpdateGit },
  ]
  const updateGitRules: FormRules = {
    gitee: [{ required: true, message: '请输入gitee地址', trigger: 'blur' }],
    github: [{ required: true, message: '请输入github地址', trigger: 'blur' }],
  }
</script>

<style scoped>
  .user-container {
    display: flex;
  }

  .user-profile {
    position: relative;
  }

  .user-profile-bg {
    width: 100%;
    height: 200px;
    background-image: url('@/assets/img/ucenter-bg.jpg');
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
  }

  .user-profile {
    width: 500px;
    margin-right: 20px;
    flex: 0 0 auto;
    align-self: flex-start;
  }

  .user-avatar-wrap {
    position: absolute;
    top: 135px;
    width: 100%;
    text-align: center;
  }

  .user-avatar {
    border: 5px solid #fff;
    border-radius: 50%;
    overflow: hidden;
    box-shadow: 0 7px 12px 0 rgba(62, 57, 107, 0.16);
  }

  .user-info {
    text-align: center;
    padding: 80px 0 30px;
  }

  .info-name {
    margin: 0 0 20px;
    font-size: 22px;
    font-weight: 500;
    color: #373a3c;
  }

  .info-desc {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 5px;
  }

  .info-desc,
  .info-desc a {
    font-size: 18px;
    color: #55595c;
  }

  .info-icon {
    margin-top: 10px;
  }

  .info-icon i {
    font-size: 30px;
    margin: 0 10px;
    color: #343434;
  }

  .user-content {
    flex: 1;
    height: 600px; /* 设置固定高度 */
  }

  .user-content :deep(.el-tabs) {
    height: 100%;
    display: flex;
  }

  .user-content :deep(.el-tabs__header) {
    margin-right: 20px;
  }

  .user-content :deep(.el-tabs__content) {
    flex: 1;
    overflow: hidden;
  }

  .user-tab-pane {
    height: 100%;
    overflow-y: auto;
    overflow-x: hidden;
    /* 为滚动条预留空间 */
    padding-right: 28px;
  }

  /* 自定义滚动条样式 */
  .user-tab-pane::-webkit-scrollbar {
    width: 8px;
  }

  .user-tab-pane::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 4px;
  }

  .user-tab-pane::-webkit-scrollbar-thumb {
    background: #888;
    border-radius: 4px;
  }

  .user-tab-pane::-webkit-scrollbar-thumb:hover {
    background: #555;
  }

  .user-footer {
    display: flex;
    border-top: 1px solid rgba(83, 70, 134, 0.1);
  }

  .user-footer-item {
    padding: 20px 0;
    width: 50%;
    text-align: center;
  }

  .user-footer > div + div {
    border-left: 1px solid rgba(83, 70, 134, 0.1);
  }
</style>
